<?php
require_once 'auth.php';
requireLogin();

$error = $product_name = $sku = $quantity = $location = '';
$success = ''; // 初始化 $success 变量

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $conn = dbConnect();
    if (!$conn) {
        $error = '数据库连接失败，请重试';
    } else {
        $product_name = trim($_POST['product_name']);
        $sku = trim($_POST['sku']);
        $quantity = (int)$_POST['quantity'];
        $location = trim($_POST['location']);

        // 数据验证
        if (empty($product_name) || empty($sku) || empty($location)) {
            $error = '请填写所有必填字段';
        } elseif ($quantity < 0) {
            $error = '数量不能为负数';
        } else {
            // 检查SKU是否重复
            $checkStmt = $conn->prepare("SELECT id FROM inventory WHERE sku = ?");
            $checkStmt->bind_param('s', $sku);
            $checkStmt->execute();
            if ($checkStmt->get_result()->num_rows > 0) {
                $error = 'SKU已存在';
            } else {
                // 插入库存记录
                $insertStmt = $conn->prepare("INSERT INTO inventory (product_name, sku, quantity, location) VALUES (?, ?, ?, ?)");
                $insertStmt->bind_param('ssis', $product_name, $sku, $quantity, $location);

                if ($insertStmt->execute()) {
                    $newId = $conn->insert_id;

                    // 记录操作日志
                    $logStmt = $conn->prepare("INSERT INTO operation_logs (user_id, operation_type, target_id, details) VALUES (?, 'add', ?, ?)");
                    $details = "新增商品: {$product_name} (SKU: {$sku}) 数量: {$quantity} 位置: {$location}";
                    $logStmt->bind_param('iis', $_SESSION['user_id'], $newId, $details);
                    $logStmt->execute();
                    // 关闭数据库连接
                    $insertStmt->close();
                    $logStmt->close();
                    $conn->close();
                    $success = '添加成功';

                    // header('Location: inventory.php');
                    // exit;
                } else {
                    $error = '保存失败，请重试';
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>新增商品</title>
    <link rel="stylesheet" href="/dist/css/tabler.min.css">
</head>

<body class="layout-fluid layout-vertical">
    <?php include 'navbar.php'; ?>

    <div class="page">
        <div class="container-fluid">
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">新增商品</h3>
                            <div class="ms-auto">
                                <a href="inventory.php" class="btn btn-secondary">返回列表</a>
                            </div>
                        </div>
                        <div class="card-body">
                            <?php if (!empty($error)): ?>
                                <div class="alert alert-danger" role="alert">
                                    <div class="alert-icon">
                                        <!-- Download SVG icon from http://tabler.io/icons/icon/alert-circle -->
                                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"
                                            viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
                                            stroke-linecap="round" stroke-linejoin="round"
                                            class="icon alert-icon icon-2">
                                            <path d="M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0" />
                                            <path d="M12 8v4" />
                                            <path d="M12 16h.01" />
                                        </svg>
                                    </div>
                                    <?= htmlspecialchars($error) ?>
                                </div>
                            <?php endif; ?>
                            <?php if (!empty($success)): ?>
                                <div class="alert alert-success" role="alert">
                                    <div class="alert-icon">
                                        <!-- Download SVG icon from http://tabler.io/icons/icon/check -->
                                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"
                                            viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
                                            stroke-linecap="round" stroke-linejoin="round"
                                            class="icon alert-icon icon-2">
                                            <path d="M5 12l5 5l10 -10" />
                                        </svg>
                                    </div>
                                    <div>
                                        <h4 class="alert-heading">Wow! Everything worked!</h4>
                                        <div class="alert-description">
                                            <?= htmlspecialchars($success) ?>
                                        </div>
                                    </div>
                                </div>
                            <?php endif; ?>

                            <form method="post">
                                <div class="mb-3">
                                    <label for="product_name" class="form-label">商品名称 *</label>
                                    <input type="text" class="form-control" name="product_name" value="<?= isset($_POST['product_name']) ? htmlspecialchars($_POST['product_name']) : '' ?>" required>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">SKU编码 *</label>
                                    <input type="text" class="form-control" name="sku" value="<?= isset($_POST['sku']) ? htmlspecialchars($_POST['sku']) : '' ?>" required>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">初始数量</label>
                                    <input type="number" class="form-control" name="quantity" value="<?= isset($_POST['quantity']) ? (int)$_POST['quantity'] : 0 ?>" min="0">
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">存储位置 *</label>
                                    <input type="text" class="form-control" name="location" value="<?= isset($_POST['location']) ? htmlspecialchars($_POST['location']) : '' ?>" required>
                                </div>

                                <div class="mt-4">
                                    <button type="submit" class="btn btn-primary">保存商品</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="/dist/js/tabler.min.js"></script>
</body>

</html>